//
//  MKUIPopoverMenu.m
//  MKUI
//
//  Created by 苏尚进 on 2024/11/25.
//  Copyright © 2024 moon. All rights reserved.
//

#import "MKUIPopoverMenu.h"
#import "MKUICollectionView.h"
#import "UIColor+MKUI.h"
#import "UICollectionViewFlowLayout+MKUI.h"
@implementation MKUIPopoverMenu
- (id)init{
    if(self=[super init]){
        self.shouldDismissWhenClick = YES;
    }
    return self;
}
+ (instancetype)menuWithTitle:(nullable NSString *)title image:(nullable UIImage *)image darkImage:(nullable UIImage *)darkImage whenClick:(void(^ _Nullable)(MKUIPopoverMenu *menu))whenClick{
    MKUIPopoverMenu *menu = [[self alloc] init];
    menu.title = title;
    menu.image = image;
    menu.darkImage = darkImage;
    menu.whenClick = whenClick;
    return menu;
}
+ (instancetype)menuWithTitle:(nullable NSString *)title whenClick:(void(^ _Nullable)(MKUIPopoverMenu *menu))whenClick{
    return [self menuWithTitle:title image:nil darkImage:nil whenClick:whenClick];
}
@end

@interface MKUIPopoverMenuItemCollectionViewCell()
@property(nonatomic,strong) MKUIFlowLayoutButton *menuButton;
@end
@implementation MKUIPopoverMenuItemCollectionViewCell
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.menuButton = [[MKUIFlowLayoutButton alloc] init];
        self.menuButton.contentStyle = MKUIFlowLayoutButtonContentStyleVertical;
        self.menuButton.interitemSpacing = 8;
        self.menuButton.contentInsets = MKUIEdgeInsetsMakeSameEdge(1);
        self.menuButton.imageSize = CGSizeMake(20, 20);
        self.menuButton.hideImageViewForNoImage = NO;
        self.menuButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.menuButton setTitleColor:[UIColor mk_colorWithLight:UIColor.whiteColor] forState:(UIControlStateNormal)];
        [self.menuButton setTitleColor:[UIColor mk_colorWithLight:UIColor.whiteColor.mk_halfColor] forState:(UIControlStateHighlighted)];
        [self.menuButton addTarget:self action:@selector(_onMenuButtonDidTap:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.contentView addSubview:self.menuButton];
    }
    return self;
}
- (void)_onMenuButtonDidTap:(id)sender{
    [self.collectionCellModel didClickSelf];
}
- (MKUIPopoverMenu *)popoverMenu{
    id modelValue = self.collectionCellModel.modelValue;
    if([modelValue isKindOfClass:MKUIPopoverMenu.class]) return modelValue;
    return nil;
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    self.menuButton.frame = bounds;
}
- (CGSize)customSizeThatFits:(CGSize)size{
    return CGSizeMake(50, 50);
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    MKUIPopoverMenu *modelValue = self.popoverMenu;
    UIImage *image = modelValue.image;
    if (@available(iOS 12.0, *)) {
        BOOL isDark = self.traitCollection.userInterfaceStyle==UIUserInterfaceStyleDark;
        image = isDark&&modelValue.darkImage?modelValue.darkImage:modelValue.image;
    }
    [self.menuButton setTitle:modelValue.title forState:(UIControlStateNormal)];
    [self.menuButton setImage:image forState:(UIControlStateNormal)];
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 12.0, *)) {
        BOOL isDark = previousTraitCollection.userInterfaceStyle==UIUserInterfaceStyleDark;
        MKUIPopoverMenu *modelValue = self.popoverMenu;
        [self.menuButton setImage:isDark&&modelValue.darkImage?modelValue.darkImage:modelValue.image forState:UIControlStateNormal];
    }
}
+ (CGSize)dynamicSizeWithCollectionView:(UICollectionView *)collectionView collectionCellModel:(MKUICollectionViewCellModel *)collectionCellModel cellShareInstance:(UICollectionViewCell<MKUICollectionViewCellProtocol> *)cell calBlock:(CGSize(^)(UICollectionView *collectionView,MKUICollectionViewCellModel *cellModel,id cell))block{
    return CGSizeMake(50, 50);
}
@end

@interface MKUIPopoverMenuCollectionView(){
    NSMutableArray<MKUIPopoverMenu *> *_popoverMenus;
    BOOL _needReloadMenus;
}
@property(nonatomic,strong) MKUICollectionView *collectionView;
@property(nonatomic,strong) UICollectionViewFlowLayout *flowCollectionViewLayout;
@end

@implementation MKUIPopoverMenuCollectionView
- (id)init{
    if(self=[super init]){
        _needReloadMenus = YES;
        _popoverMenus = [[NSMutableArray alloc] init];
        self.cellClass = MKUIPopoverMenuItemCollectionViewCell.class;
        self.flowCollectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
        self.flowCollectionViewLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        self.flowCollectionViewLayout.minimumLineSpacing = 5;
        self.flowCollectionViewLayout.minimumInteritemSpacing = 5;
        self.flowCollectionViewLayout.sectionInset = UIEdgeInsetsZero;

        self.collectionView = [[MKUICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowCollectionViewLayout];
        if (@available(iOS 11.0, *)) {
            self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.collectionView.backgroundColor = UIColor.clearColor;
        self.collectionView.bounces = NO;
        self.contentView = self.collectionView;
        self.permittedArrowDirections = UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown;
    }
    return self;
}
- (void)setPopoverMenus:(NSArray<MKUIPopoverMenu *> *)popoverMenus{
    [_popoverMenus removeAllObjects];
    [_popoverMenus addObjectsFromArray:popoverMenus];
    [self setNeedsReload];
}
- (NSArray<MKUIPopoverMenu *> *)popoverMenus{
    return [_popoverMenus copy];
}
- (void)addMenu:(nullable MKUIPopoverMenu *)menu{
    if(!menu)return;
    [_popoverMenus addObject:menu];
    [self setNeedsReload];
}
- (void)setNeedsReload{
    _needReloadMenus = YES;
    [super setNeedsReload];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    [self _reloadMenus];
}
- (void)_reloadMenus{
    if(!_needReloadMenus) return;
    _needReloadMenus = NO;
    [self reloadMenus];
}
- (Class)menuCellClassForMenu:(MKUIPopoverMenu *)menu{
    Class cellClass = self.cellClass?:MKUIPopoverMenuItemCollectionViewCell.class;
    return cellClass;
}
- (void)reloadMenus{
    MKUICollectionViewModel *model = self.collectionView.model;
    [model removeAllSectionModels];
    @MK_WEAKIFY(self);
    for(MKUIPopoverMenu *menu in _popoverMenus){
        Class cellClass = [self menuCellClassForMenu:menu];
        MKUICollectionViewCellModel *cm = [MKUICollectionViewCellModel modelWithValue:menu cellClass:cellClass whenClick:^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
            @MK_NORMALIZE(self);
            if(menu.shouldDismissWhenClick){
                [self dismissPopoverAnimated:YES completion:^(BOOL finished) {
                    if(menu.whenClick){
                        menu.whenClick(menu);
                    }
                }];
            }else{
                if(menu.whenClick){
                    menu.whenClick(menu);
                }
            }
        }];
        [model addCellModel:cm];
    }
    [model reloadCollectionViewData];
}
- (CGSize)contentViewSizeThatFits:(CGSize)size{
    CGSize s = [self.flowCollectionViewLayout mk_sizeThatFits:size];
    s.height = MIN(size.height,s.height);
    return s;
}
- (void)layoutSelfInContainerView{
    [self _reloadMenus];
    [super layoutSelfInContainerView];
}
@end

@interface MKUIPopoverMenuListViewCell()
@property(nonatomic,strong) MKUIFlowLayoutButton *menuButton;
@end
@implementation MKUIPopoverMenuListViewCell
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.selectedBackgroundColor = UIColor.mk_popoverMenuCellSelectedColor;
        self.menuButton = [[MKUIFlowLayoutButton alloc] init];
        self.menuButton.contentStyle = MKUIFlowLayoutButtonContentStyleHorizontal;
        self.menuButton.interitemSpacing = 8;
        self.menuButton.imageSize = CGSizeMake(20, 20);
        self.menuButton.hideImageViewForNoImage = YES;
        self.menuButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.menuButton setTitleColor:[UIColor mk_colorWithLight:UIColor.whiteColor] forState:(UIControlStateNormal)];
        [self.menuButton setTitleColor:[UIColor mk_colorWithLight:UIColor.whiteColor.mk_halfColor] forState:(UIControlStateHighlighted)];
        [self.menuButton addTarget:self action:@selector(_onMenuButtonDidTap:) forControlEvents:(UIControlEventTouchUpInside)];
        self.menuButton.hideImageViewForNoImage = YES;
        self.menuButton.enabled = NO;
        [self.contentView addSubview:self.menuButton];
    }
    return self;
}
- (void)_onMenuButtonDidTap:(id)sender{
    if(self.whenClick){
        self.whenClick(self);
    }
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.contentView.bounds;
    self.menuButton.frame = bounds;
}
- (UIEdgeInsets)safeAreaInsets{
    return UIEdgeInsetsZero;
}
- (CGSize)sizeThatFits:(CGSize)size{
    CGSize s = [self.menuButton sizeThatFits:size];
    s.height = 40;//高度固定为40
    return s;
}
- (void)setScrollDirection:(MKUIListViewScrollDirection)scrollDirection{
    if(_scrollDirection==scrollDirection)return;
    _scrollDirection = scrollDirection;
}
- (void)setPopoverMenu:(MKUIPopoverMenu *)popoverMenu{
    if(_popoverMenu==popoverMenu)return;
    _popoverMenu = popoverMenu;
}
- (void)reloadMenu{
    if(self.scrollDirection==MKUIListViewScrollDirectionHorizontal){//菜单水平排列
        self.menuButton.layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentCenter;
        self.menuButton.contentInsets = UIEdgeInsetsMake(1, 10, 1, 10);
    }else{//菜单竖向排列
        self.menuButton.layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentLeft;
        self.menuButton.contentInsets = UIEdgeInsetsMake(1, 20, 1, 20);
    }
    MKUIPopoverMenu *modelValue = self.popoverMenu;
    UIImage *image = modelValue.image;
    if (@available(iOS 12.0, *)) {
        BOOL isDark = self.traitCollection.userInterfaceStyle==UIUserInterfaceStyleDark;
        image = isDark&&modelValue.darkImage?modelValue.darkImage:modelValue.image;
    }
    [self.menuButton setTitle:modelValue.title forState:(UIControlStateNormal)];
    [self.menuButton setImage:image forState:(UIControlStateNormal)];
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 12.0, *)) {
        BOOL isDark = previousTraitCollection.userInterfaceStyle==UIUserInterfaceStyleDark;
        MKUIPopoverMenu *modelValue = self.popoverMenu;
        [self.menuButton setImage:isDark&&modelValue.darkImage?modelValue.darkImage:modelValue.image forState:UIControlStateNormal];
    }
}
@end

@interface MKUIPopoverMenuListView(){
    NSMutableArray<MKUIPopoverMenu *> *_popoverMenus;
    BOOL _needReloadMenus;
}
@property(nonatomic,strong) MKUIListView *listView;
@end
@implementation MKUIPopoverMenuListView
- (id)init{
    if(self=[super init]){
        _needReloadMenus = YES;
        _popoverMenus = [[NSMutableArray alloc] init];
        self.cellClass = MKUIPopoverMenuListViewCell.class;
        self.listView = [[MKUIListView alloc] init];
        self.listView.clipsToBounds = YES;
        self.listView.separatorStyle = MKUIListViewCellSeparatorStyleSingleLine;
        self.listView.style = MKUIListViewStylePlain;
        self.listView.cellInteritemSpacing = 0;
        self.listView.separatorColor = UIColor.mk_listViewSeparatorColor;
        self.scrollDirection = MKUIListViewScrollDirectionHorizontal;
        if (@available(iOS 11.0, *)) {
            self.listView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.listView.groupBackgroundColor = UIColor.clearColor;
        self.listView.backgroundColor = UIColor.clearColor;
        self.listView.showsHorizontalScrollIndicator = NO;
        self.listView.showsVerticalScrollIndicator = NO;
        self.contentView = self.listView;
        self.contentInsets = MKUIEdgeInsetsMakeSameEdge(1);
        self.permittedArrowDirections = UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown;
    }
    return self;
}
- (void)setScrollDirection:(MKUIListViewScrollDirection)scrollDirection{
    if(self.scrollDirection==scrollDirection)return;
    self.listView.scrollDirection = scrollDirection;
    [self setNeedsReload];
}
- (MKUIListViewScrollDirection)scrollDirection{
    return self.listView.scrollDirection;
}
- (void)setPopoverMenus:(NSArray<MKUIPopoverMenu *> *)popoverMenus{
    [_popoverMenus removeAllObjects];
    [_popoverMenus addObjectsFromArray:popoverMenus];
    [self setNeedsReload];
}
- (NSArray<MKUIPopoverMenu *> *)popoverMenus{
    return [_popoverMenus copy];
}
- (void)addMenu:(nullable MKUIPopoverMenu *)menu{
    if(!menu)return;
    [_popoverMenus addObject:menu];
    [self setNeedsReload];
}
- (void)setNeedsReload{
    _needReloadMenus = YES;
    [super setNeedsReload];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    [self _reloadMenus];
}
- (Class)menuCellClassForMenu:(MKUIPopoverMenu *)menu{
    Class cellClass = self.cellClass?:MKUIPopoverMenuListViewCell.class;
    return cellClass;
}
- (void)_reloadMenus{
    if(!_needReloadMenus) return;
    _needReloadMenus = NO;
    [self reloadMenus];
}
- (void)customMenuCell:(__kindof MKUIPopoverMenuListViewCell *)cell{
}
- (void)reloadMenus{
    self.listView.layer.cornerRadius = self.borderView.cornerRadius;
    [self.listView deleteAllSections];
    
    @MK_WEAKIFY(self);
    for(MKUIPopoverMenu *menu in _popoverMenus){
        Class cellClass = [self menuCellClassForMenu:menu];
        MKUIPopoverMenuListViewCell *cell = [[cellClass alloc] init];
        cell.popoverMenu = menu;
        cell.scrollDirection = self.scrollDirection;
        cell.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            if(menu.shouldDismissWhenClick){
                [self dismissPopoverAnimated:YES completion:^(BOOL finished) {
                    if(menu.whenClick){
                        menu.whenClick(menu);
                    }
                }];
            }else{
                if(menu.whenClick){
                    menu.whenClick(menu);
                }
            }
        };
        [cell reloadMenu];
        [self customMenuCell:cell];
        [self.listView addItem:cell];
    }
    [self.listView reloadData];
    UIEdgeInsets separatorInsets = UIEdgeInsetsZero;
    if(self.scrollDirection==MKUIListViewScrollDirectionVertical){
        separatorInsets.left = separatorInsets.right = 15;
    }
    self.listView.separatorInsets = separatorInsets;
}
- (CGSize)contentViewSizeThatFits:(CGSize)size{
    CGSize s = size;
    if(self.scrollDirection==MKUIListViewScrollDirectionHorizontal){
        CGFloat height = 40;
        size.height = height;
        s = [self.listView sizeThatFits:size];
        s.width = MIN(size.width,s.width);
        s.height = height;
    }else{
        s = [self.listView sizeThatFits:size unlimit:YES];
        s.width = MIN(s.width,size.width);
        s.height = MIN(s.height,size.height);
    }
    return s;
}
- (void)layoutSelfInContainerView{
    [self _reloadMenus];
    [super layoutSelfInContainerView];
}
@end
